package com.example.leetcode;

import java.util.HashMap;
import java.util.Map;

public class 两数之和 {

    /**
     * 法一 暴力枚举
     */
    public static int[] twoSum(int[] nums, int target) {
        int[] index = new int[2];
        int k = 0;
        for (int i = 0; i < nums.length; i++) {
            for (int j = i+1 ; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    index[k++] = i;
                    index[k++] = j;
                    break;
                }
            }
        }
        return index;
    }

    /**
     * 法二 哈希表
     * 执行用时分布，击败95.58%使用Java的用户
     */
    public static int[] twoSum1(int[] nums, int target) {
        Map<Integer, Integer> hashTable = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (hashTable.containsKey(target - nums[i])) {
                return new int[]{hashTable.get(target - nums[i]), i};
            }
            hashTable.put(nums[i], i);
        }
        return new int[0];
    }


    /*
      [I@6a6824be
      [I@5c8da962
      [I@512ddf17

      [I@6a6824be
      [I@5c8da962
      [I@512ddf17

     */
    public static void main(String[] args) {
        int[] nums1 = new int[]{2, 7, 11, 15};
        int target1 = 9;
        System.out.println(twoSum1(nums1, target1));

        int[] nums2 = new int[]{3, 2, 4};
        int target2 = 6;
        System.out.println(twoSum1(nums2, target2));

        int[] nums3 = new int[]{3, 3};
        int target3 = 9;
        System.out.println(twoSum1(nums3, target3));
    }




}
